package com.practice.backend.Controller;


import com.practice.backend.Common.Result;
import com.practice.backend.Entity.Goods;
import com.practice.backend.Repository.GoodsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsRepository goodsRepository;


    @RequestMapping("/findAll")
    public Result findAll(@Param("pageNum") int pageNum, @Param("pageSize") int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        Page<Goods> goodsPage = goodsRepository.findAll(pageable);
        return Result.success(true, "查询成功", (int) goodsPage.getTotalElements(), goodsPage.getContent());
    }

    @RequestMapping("/findByName")
    public Result findAll(@Param("pageNum") int pageNum, @Param("pageSize") int pageSize, @Param("name") String name) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        //模糊搜索
        Page<Goods> goodsRepositoryByName = goodsRepository.findByNameLike("%" + name + "%",pageable);
        if (goodsRepositoryByName.getTotalElements() == 0) {
            return Result.error(false, "未找到", 0, null);
        }
        return Result.success(true, "查询成功", (int) goodsRepositoryByName.getTotalElements(), goodsRepositoryByName.getContent());
    }

}
